import os
from fastapi import APIRouter,HTTPException,status,Query,Depends,Header
from fastapi.exceptions import HTTPException
from typing import Optional

app07 = APIRouter()

@app07.get("/")
async def index():
    return {
        "name":os.path.basename(__file__)
    }

async def paging_query(q:Optional[str]=None,page:int= 1,limits:int= 10):
    return {
        "q":q,
        "page":page,
        "limits":limits
    }

@app07.get("/users")
async def query_users(users:dict = Depends(paging_query)):
    return users

@app07.get("/books")
def query_books(books:dict = Depends(paging_query)):
    return books

"""*********************    类依赖  ***********************"""

class QueryParams:
    def __init__(self,q:Optional[str]=None,page:int= 1,limits:int= 10):
        self.page = page
        self.limits = limits
        self.q = q

users = [
    {"name":"jack"},
    {"name":"mike"},
    {"name":"rose"},
    {"name":"luci"},
]
@app07.get("/users/class_depends")
async def query_users2(params = Depends(QueryParams)):
    response = {}
    if params.q:
        response.update({"q":params.q})
    items = users[params.page : params.page + params.limits]
    response.update({"items":items})
    return response


"""************ 路径操作使用依赖 ***********"""

async def validate_token(x_token:str = Header(...)):
    if x_token != "mytoken":
        raise HTTPException(status_code=400,detail="无效Token")
    return x_token

async def validate_key(x_key:str = Header(...)):
    if x_key != "mykey":
        raise HTTPException(status_code=400,detail="无效Key")
    return x_key

@app07.get("/path_depends",dependencies=[Depends(validate_key),Depends(validate_token)])
async def path_depends():
    return users